import React, { Component } from 'react'
import {
  Text,
  View,
  StyleSheet,
  Platform,
  ScrollView,
  TextInput,
  TouchableOpacity,
  DeviceEventEmitter,
  NativeAppEventEmitter,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import AMapLocation from 'react-native-amap-location'
import Item from '../component/Item'
import Button from '../component/Button'
import RootView from '../component/RootView'
import Base from './Base'
import { NavigationActions, px2dp } from '../utils'
import { toast } from '../utils/toast'
import * as addressService from '../services/address'

class EditAddress extends Base {
  constructor(props) {
    super(props)
    this.state = {
      address: Immutable.Map(),
      village: {},
      location: {},
    }
    this.subscription = null
    this.subscriptionLocation = null
  }
  static navigationOptions = {
    title: '地址',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  }
  loadData(addressId) {
    this.setState({ fetching: true })
    this.request(addressService.detail({ id: addressId })).then(data => {
      this.setState({
        fetching: false,
        address: Immutable.fromJS(data.data),
      })
    })
  }
  save(params) {
    this.setState({ fetching: true })
    const { key, parentKey, selectable } = this.props.navigation.state.params
    addressService
      .save(params)
      .then(data => {
        this.setState({ fetching: false })

        if (selectable) {
          this.setParams(parentKey, { addressId: data.id })
          this.goBack(key)
          return
        }
        this.setParams(key, { reload: 1 })

        this.goBack()
      })
      .catch(e => {
        this.setState({ fetching: false })
        toast(e.msg)
      })
  }
  update(params) {
    this.setState({ fetching: true })
    const { key, parentKey, selectable } = this.props.navigation.state.params
    addressService
      .update(params)
      .then(data => {
        this.setState({ fetching: false })
        if (selectable) {
          this.setParams(parentKey, { addressId: params.id })
          this.goBack(key)
          return
        }
        this.setParams(key, { reload: 1 })
        this.goBack()
      })
      .catch(e => {
        this.setState({ fetching: false })
        toast(e.msg)
      })
  }
  remove(id) {
    const { key } = this.props.navigation.state.params
    this.request(addressService.remove({ id })).then(data => {
      this.setParams(key, { reload: 1 })
      this.goBack()
    })
  }

  submit() {
    const { address, location, village } = this.state
    const params = {
      name:
        this.refs.name._lastNativeText ||
        this.refs.name.props.defaultValue ||
        '',
      phone:
        this.refs.phone._lastNativeText ||
        this.refs.phone.props.defaultValue ||
        '',
      room:
        this.refs.room._lastNativeText ||
        this.refs.room.props.defaultValue ||
        '',
    }

    if (location.name) {
      params.village = location.name
      params.city = location.city
      params.district = location.district
    }
    if (village.name) {
      params.village = village.name
      params.city = village.city
      params.district = village.district
    }

    if (address.get('id')) {
      params.id = address.get('id')
      if (!params.village) {
        params.village = address.get('village')
        params.city = address.get('city')
        params.district = address.get('district')
      }
      this.update(params)
    } else {
      this.save(params)
    }
  }

  onLocationEvent(data) {
    this.setState({ village: data })
  }
  componentWillUnmount() {
    this.subscription.remove()
  }

  componentDidMount() {
    this.subscription = DeviceEventEmitter.addListener(
      'address.location',
      this.onLocationEvent.bind(this)
    )

    const { addressId } = this.props.navigation.state.params
    if (addressId) {
      this.loadData(addressId)
    }
  }
  render() {
    const { fetching, village, address, location } = this.state
    let villageText = '点击选择'
    if (address && address.get('village')) {
      villageText = address.get('village')
    }
    if (!address.get('id') && location.name) {
      villageText = location.name
    }
    if (village && village.name) {
      villageText = village.name
    }

    return (
      <RootView
        fetching={fetching}
        onModalClose={() => this.onModalClose()}
        style={styles.container}
      >
        <ScrollView style={{ flex: 1 }}>
          <View
            style={{ marginTop: 10, backgroundColor: '#fff', paddingLeft: 16 }}
          >
            <View style={styles.item}>
              <Text style={styles.label}>{'联系人'}</Text>
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <TextInput
                  ref="name"
                  defaultValue={address.get('name')}
                  underlineColorAndroid="transparent"
                  autoCapitalize={'none'}
                  ref={'name'}
                  style={styles.textInput}
                  placeholder="姓名"
                  placeholderTextColor="#aaa"
                />
              </View>
            </View>
            <View style={styles.item}>
              <Text style={styles.label}>{'电话'}</Text>
              <View style={{ flex: 1 }}>
                <TextInput
                  ref="phone"
                  defaultValue={address.get('phone')}
                  underlineColorAndroid="transparent"
                  keyboardType={'numeric'}
                  style={styles.textInput}
                  placeholder="收货人电话"
                  placeholderTextColor="#aaa"
                />
              </View>
            </View>
            <View style={styles.item}>
              <Text style={styles.label}>{'小区'}</Text>
              <View style={{ flex: 1 }}>
                <TouchableOpacity
                  onPress={() => this.goto('Village', { key: 'address' })}
                >
                  <Text style={styles.villageInput}>{villageText}</Text>
                </TouchableOpacity>
              </View>
            </View>
            <View style={styles.item}>
              <Text style={styles.label}>{'门牌号'}</Text>
              <View style={{ flex: 1 }}>
                <TextInput
                  ref="room"
                  defaultValue={address.get('room')}
                  underlineColorAndroid="transparent"
                  style={styles.textInput}
                  placeholder="例：2号楼6C021"
                  placeholderTextColor="#aaa"
                />
              </View>
            </View>
          </View>
        </ScrollView>
        <Button
          style={{
            height: px2dp(45),
          }}
          onPress={() => this.submit()}
        >
          <View
            style={{
              flexDirection: 'row',
              backgroundColor: '#fff',
              flex: 1,
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Text style={{ color: '#0096ff' }}>{'确定'}</Text>
          </View>
        </Button>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    borderBottomWidth: 1,
    borderBottomColor: '#f8f8f8',
    paddingVertical: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  active: {
    borderColor: '#81c2ff',
    color: '#0096ff',
  },
  label: {
    width: 45,
    height: 36,
    paddingVertical: 10,
    color: '#222',
    justifyContent: 'center',
  },
  villageInput: {
    flex: 1,
    paddingVertical: 10,
    height: 36,
    alignItems: 'center',
    paddingHorizontal: 10,
  },
  textInput: {
    flex: 1,
    paddingVertical: 0,
    height: 36,
    fontSize: 14,
    paddingHorizontal: 10,
  },
})

export default EditAddress
